package com.rds.web.controller.system;

import com.rds.common.constant.UserConstants;
import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.SysCompany;
import com.rds.common.core.domain.entity.SysDept;
import com.rds.common.utils.StringUtils;
import com.rds.system.service.ISysCompanyService;
import com.rds.system.service.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 公司信息Controller
 */
@RestController
@RequestMapping("/system/company")
public class SysCompanyController extends BaseController {
    @Autowired
    private ISysCompanyService companyServiceny;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取公司列表
     */
    @PreAuthorize("@ss.hasPermi('system:company:list')")
    @GetMapping("/list")
    public AjaxResult list(SysCompany sysCompany)
    {
        sysCompany.setDelFlag('0');
        List<SysDept>  deptlist=deptService.selectDeptList(new SysDept());
        List<SysCompany>  list=companyServiceny.selectSysCompanyList(sysCompany);
        List<SysCompany>  list2=new ArrayList<>();
        for (SysCompany company: list) {
            company.setCompanyOrDept("1");
            list2.add(company);
        }
        for (SysDept dept: deptlist) {
            SysCompany company2=new SysCompany();
            company2.setCompanyId(dept.getDeptId());
            company2.setParentId(dept.getParentId());
            company2.setAncestors(dept.getAncestors());
            company2.setCompanyName(dept.getDeptName());
            company2.setOrderNum(Long.valueOf(dept.getOrderNum()));
            company2.setStatus(dept.getStatus());
            company2.setCreateTime(dept.getCreateTime());
            company2.setTel(dept.getTel());
            company2.setEmail(dept.getEmail());
            company2.setCharge(dept.getCharge());
            company2.setCompanyOrDept("2");
            list2.add(company2);
        }
        return AjaxResult.success(list2);
    }

    /**
     * 根据公司编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:company:query')")
    @GetMapping(value = "/{companyId}")
    public AjaxResult getInfo(@PathVariable Long companyId)
    {
        SysCompany company=companyServiceny.selectSysCompanyDeptById(companyId);
        if(company==null){
            SysCompany company2=new SysCompany();
            SysDept dept=deptService.selectDeptById(companyId);
            company2.setCompanyId(dept.getDeptId());
            company2.setParentId(dept.getParentId());
            company2.setDeptName(dept.getDeptName());
            company2.setOrderNum(Long.valueOf(dept.getOrderNum()));
            company2.setStatus(dept.getStatus());
            company2.setTel(dept.getTel());
            company2.setEmail(dept.getEmail());
            company2.setCharge(dept.getCharge());
            company2.setCompanyOrDept("2");
            return AjaxResult.success(company2);
        }else{
            company.setCompanyOrDept("1");
            return AjaxResult.success(company);
        }
    }

    /**
     * 查询公司列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:company:list')")
    @GetMapping("/list/exclude/{companyId}")
    public AjaxResult excludeChild(@PathVariable(value = "companyId", required = false) Long companyId)
    {
        List<SysCompany> compans=companyServiceny.selectSysCompanyList(new SysCompany());
        Iterator<SysCompany> it = compans.iterator();
        while (it.hasNext())
        {
            SysCompany d=  (SysCompany)it.next();
            if (d.getCompanyId().intValue() == companyId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), companyId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(compans);
    }

    /**
     * 新增公司
     */
    @PreAuthorize("@ss.hasPermi('system:company:add')")
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody SysCompany sysCompany){
        if("2".equals(sysCompany.getCompanyOrDept())){
            SysDept dept=new SysDept();
            dept.setDeptName(sysCompany.getDeptName());
            dept.setParentId(sysCompany.getParentId());
            if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
            {
                return AjaxResult.error("新增部门'" + sysCompany.getCompanyName() + "'失败，部门名称已存在");
            }
        }else{
            if (UserConstants.NOT_UNIQUE.equals(companyServiceny.checkCompanyNameUnique(sysCompany)))
            {
                return AjaxResult.error("新增公司'" + sysCompany.getCompanyName() + "'失败，公司名称已存在");
            }
        }
        return toAjax(companyServiceny.insertSysCompany(sysCompany));
    }

    /**
     * 修改公司
     */
    @PreAuthorize("@ss.hasPermi('system:company:edit')")
    @PutMapping
    @Transactional
    public AjaxResult edit(@Validated @RequestBody SysCompany sysCompany) {
        if (UserConstants.NOT_UNIQUE.equals(companyServiceny.checkCompanyNameUnique(sysCompany))) {
            return AjaxResult.error("修改公司'" + sysCompany.getCompanyName() + "'失败，公司名称已存在");
        }else if(sysCompany.getParentId().equals(sysCompany.getCompanyId())){
            return AjaxResult.error("修改公司'" + sysCompany.getCompanyName()+ "'失败，上级公司不能是自己");
        }else if(StringUtils.equals(UserConstants.DEPT_DISABLE, sysCompany.getStatus()) && companyServiceny.selectNormalChildrenCompanyById(sysCompany.getCompanyId()) > 0){
            return AjaxResult.error("该公司包含未停用的子公司！");
        }
        return toAjax(companyServiceny.updateSysCompany(sysCompany));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:company:remove')")
    @DeleteMapping("/{companyId}")
    @Transactional
    public AjaxResult remove(@PathVariable Long companyId){
        if(companyServiceny.hasChildByCompanyId(companyId)){
            return AjaxResult.error("存在下级公司,不允许删除");
        }
        return toAjax(companyServiceny.deleteCompanyById(companyId));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:company:remove')")
    @DeleteMapping("/delDept/{deptId}")
    @Transactional
    public AjaxResult delDept(@PathVariable Long deptId){
        if(deptService.hasChildByDeptId(deptId)){
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 获取公司下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysCompany sysCompany){
        List<SysCompany>  list=companyServiceny.selectSysCompanyList(sysCompany);
        return AjaxResult.success(companyServiceny.buildCompanyTreeSelect(list));
    }

}
